"""ECB没有偏移量"""
from Crypto.Cipher import AES   # pip install pycryptodome
import base64
import json
import hashlib

AESKey = 'OGFiMGFhM2UwOGI5Y2E0Yw=='
encryptOpen = True
# encryptOpen = False


BLOCK_SIZE = 16  # Bytes
pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * \
                chr(BLOCK_SIZE - len(s) % BLOCK_SIZE)
unpad = lambda s: s[:-ord(s[len(s) - 1:])]


# 加密
def aesEncrypt(key, data):
    """
    AES的ECB模式加密方法
    :param key: **
    :param data:被加密字符串（明文）
    :return:密文
    """
    if encryptOpen:
        key = key.encode('utf8')
        jsonData = json.dumps(data)
        # 字符串补位
        data = pad(jsonData)
        cipher = AES.new(key, AES.MODE_ECB)
        # 加密后得到的是bytes类型的数据，使用Base64进行编码,返回byte字符串
        result = cipher.encrypt(data.encode())
        encodestrs = base64.b64encode(result)
        enctext = encodestrs.decode('utf8')
        return enctext
    else:
        return data


# 解密
def aesDecrypt(key, data):
    """
    :param key: **
    :param data: 加密后的数据（密文）
    :return:明文
    """
    if encryptOpen and data.get('data'):
        key = key.encode('utf8')
        data = base64.b64decode(data.get('data'))
        cipher = AES.new(key, AES.MODE_ECB)

        # 去补位
        text_decrypted = unpad(cipher.decrypt(data))
        text_decrypted = text_decrypted.decode('utf8')
        # print(text_decrypted)
        return json.loads(text_decrypted)
    else:
        return data

# MD5加密
def encrypt_MD5(data):
    md5 = hashlib.md5()       # 2，实例化md5() 方法
    md5.update(data.encode())      # 3，对字符串的字节类型加密
    result = md5.hexdigest()        # 4，加密
    return result